package com.project.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.project.demo.entity.Collect;
import com.project.demo.service.CollectService;

import com.project.demo.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.persistence.Query;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 收藏：(Collect)表控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("collect")
public class CollectController extends BaseController<Collect, CollectService> {
    /**
     * 服务对象
     */
    @Autowired
    public CollectController(CollectService service) {
        setService(service);
    }

    /**
     * 获取收藏统计数据
     * @return 统计数据（总收藏数、人均收藏数、今日收藏、本周收藏、本月收藏）
     */
    @GetMapping("statistics")
    public Map<String, Object> getStatistics() {
        try {
            log.info("========== 开始获取收藏统计数据 ==========");
            Map<String, Object> result = new HashMap<>();
            
            // 总收藏数
            String totalSql = "SELECT COUNT(*) FROM collect";
            log.info("执行SQL - 总收藏数: {}", totalSql);
            Query totalQuery = service.runCountSql(totalSql);
            Object totalObj = totalQuery.getSingleResult();
            Long total = totalObj != null ? ((Number) totalObj).longValue() : 0L;
            log.info("总收藏数查询结果: {} (原始对象: {})", total, totalObj);
            
            // 去重用户数（排除NULL和0）
            String userSql = "SELECT COUNT(DISTINCT user_id) FROM collect WHERE user_id IS NOT NULL AND user_id > 0";
            log.info("执行SQL - 去重用户数: {}", userSql);
            Query userQuery = service.runCountSql(userSql);
            Object userObj = userQuery.getSingleResult();
            Long userCount = userObj != null ? ((Number) userObj).longValue() : 0L;
            log.info("去重用户数查询结果: {} (原始对象: {})", userCount, userObj);
            
            // 人均收藏数
            double avgPerUser = userCount > 0 ? (double) total / userCount : 0.0;
            log.info("人均收藏数计算结果: {} (总收藏数: {}, 用户数: {})", avgPerUser, total, userCount);
            
            // 今日收藏数（使用DATE函数比较日期部分）
            String todaySql = "SELECT COUNT(*) FROM collect WHERE DATE(create_time) = DATE(NOW())";
            log.info("执行SQL - 今日收藏数: {}", todaySql);
            Query todayQuery = service.runCountSql(todaySql);
            Object todayObj = todayQuery.getSingleResult();
            Long today = todayObj != null ? ((Number) todayObj).longValue() : 0L;
            log.info("今日收藏数查询结果: {} (原始对象: {})", today, todayObj);
            
            // 本周收藏数（从周一开始，使用YEARWEEK函数，模式1表示从周一开始）
            String weekSql = "SELECT COUNT(*) FROM collect WHERE YEARWEEK(DATE(create_time), 1) = YEARWEEK(DATE(NOW()), 1)";
            log.info("执行SQL - 本周收藏数: {}", weekSql);
            // 先查询当前周数，用于调试
            String currentWeekSql = "SELECT YEARWEEK(DATE(NOW()), 1) as current_week";
            Query currentWeekQuery = service.runCountSql(currentWeekSql);
            Object currentWeekObj = currentWeekQuery.getSingleResult();
            log.info("当前周数: {}", currentWeekObj);
            // 查询本周的所有收藏记录，用于调试
            String weekDebugSql = "SELECT create_time, YEARWEEK(DATE(create_time), 1) as week FROM collect ORDER BY create_time DESC LIMIT 10";
            Query weekDebugQuery = service.runCountSql(weekDebugSql);
            @SuppressWarnings("unchecked")
            List<Object[]> weekDebugList = weekDebugQuery.getResultList();
            log.info("最近10条收藏记录的周数: {}", weekDebugList);
            
            Query weekQuery = service.runCountSql(weekSql);
            Object weekObj = weekQuery.getSingleResult();
            Long thisWeek = weekObj != null ? ((Number) weekObj).longValue() : 0L;
            log.info("本周收藏数查询结果: {} (原始对象: {})", thisWeek, weekObj);
            
            // 本月收藏数（使用YEAR和MONTH函数比较）
            String monthSql = "SELECT COUNT(*) FROM collect WHERE YEAR(create_time) = YEAR(NOW()) AND MONTH(create_time) = MONTH(NOW())";
            log.info("执行SQL - 本月收藏数: {}", monthSql);
            // 先查询当前年月，用于调试
            String currentMonthSql = "SELECT YEAR(NOW()) as current_year, MONTH(NOW()) as current_month";
            Query currentMonthQuery = service.runCountSql(currentMonthSql);
            Object currentMonthObj = currentMonthQuery.getSingleResult();
            log.info("当前年月: {}", currentMonthObj);
            // 查询本月的所有收藏记录，用于调试
            String monthDebugSql = "SELECT create_time, YEAR(create_time) as year, MONTH(create_time) as month FROM collect ORDER BY create_time DESC LIMIT 10";
            Query monthDebugQuery = service.runCountSql(monthDebugSql);
            @SuppressWarnings("unchecked")
            List<Object[]> monthDebugList = monthDebugQuery.getResultList();
            log.info("最近10条收藏记录的年月: {}", monthDebugList);
            
            Query monthQuery = service.runCountSql(monthSql);
            Object monthObj = monthQuery.getSingleResult();
            Long thisMonth = monthObj != null ? ((Number) monthObj).longValue() : 0L;
            log.info("本月收藏数查询结果: {} (原始对象: {})", thisMonth, monthObj);
            
            result.put("total", total.intValue());
            result.put("avgPerUser", String.format("%.2f", avgPerUser));
            result.put("today", today.intValue());
            result.put("thisWeek", thisWeek.intValue());
            result.put("thisMonth", thisMonth.intValue());
            
            JSONObject jsonResult = new JSONObject();
            jsonResult.putAll(result);
            log.info("========== 收藏统计数据最终结果 ==========");
            log.info("total={}, avgPerUser={}, today={}, thisWeek={}, thisMonth={}", 
                    total, avgPerUser, today, thisWeek, thisMonth);
            log.info("返回给前端的JSON: {}", jsonResult.toJSONString());
            log.info("==========================================");
            return success(jsonResult);
        } catch (Exception e) {
            log.error("获取收藏统计数据失败", e);
            e.printStackTrace();
            return error(50000, "获取统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取收藏月度统计数据
     * @return
     */
    @GetMapping("month_statistics")
    public Map<String, Object> getMonthStatistics() {
        try {
            // 查询最近6个月的收藏统计数据
            String sql = "SELECT DATE_FORMAT(create_time, '%Y-%m') as month, COUNT(*) as count " +
                    "FROM collect " +
                    "WHERE create_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH) " +
                    "GROUP BY DATE_FORMAT(create_time, '%Y-%m') " +
                    "ORDER BY month ASC";
            
            Query query = service.runCountSql(sql);
            @SuppressWarnings("unchecked")
            List<Object[]> resultList = query.getResultList();
            
            // 生成最近6个月的数据（确保每个月都有数据）
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
            Calendar cal = Calendar.getInstance();
            Map<String, Integer> monthMap = new LinkedHashMap<>();
            
            for (int i = 5; i >= 0; i--) {
                cal.setTime(new Date());
                cal.add(Calendar.MONTH, -i);
                String month = sdf.format(cal.getTime());
                monthMap.put(month, 0);
            }
            
            // 填充查询结果
            for (Object[] row : resultList) {
                String month = (String) row[0];
                Long count = ((Number) row[1]).longValue();
                monthMap.put(month, count.intValue());
            }
            
            // 转换为前端需要的格式
            List<Map<String, Object>> list = new ArrayList<>();
            for (Map.Entry<String, Integer> entry : monthMap.entrySet()) {
                Map<String, Object> item = new HashMap<>();
                item.put("month", entry.getKey());
                item.put("count", entry.getValue());
                list.add(item);
            }
            
            JSONObject result = new JSONObject();
            result.put("list", list);
            return success(result);
        } catch (Exception e) {
            log.error("获取收藏月度统计数据失败", e);
            return error(50000, "获取统计数据失败: " + e.getMessage());
        }
    }

}


